package com.jason.data.agentbase.agent.cglibAgent;

import com.jason.data.agentbase.agent.A;
import com.jason.data.agentbase.agent.Aimpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib 动态代理，基于继承的方式对代理目标类生成子类，但是不能是final 类型的;
 *CGLIB$intercept() 方法实际上是委托给 DynamicAdvisedInterceptor 的 intercept(),这个过程是由CGLIB库通过字节码生成技术完成的。
 */
public class CglibProxyTest implements MethodInterceptor {

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println("cglib代理-interceptor执行~~~~");

        return methodProxy.invokeSuper(o,objects);
    }


    public static  <T extends A>  A newProxyInstance(Class<T> targetInstanceClazz){
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(new CglibProxyTest());
        enhancer.setSuperclass(targetInstanceClazz);
        enhancer.setInterfaces(new Class[]{A.class});

        return  (A) enhancer.create();
    }

    public static void main(String[] args) {
        A cglibAgent = CglibProxyTest.newProxyInstance(Aimpl.class);
        cglibAgent.a();
        cglibAgent.b();
    }
}
